package com.chexiang360.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
	private static Logger log = LoggerFactory.getLogger(DateUtil.class);
	public static final SimpleDateFormat yyyy = new SimpleDateFormat("yyyy");
	public static final SimpleDateFormat MM = new SimpleDateFormat("MM");
	public static final SimpleDateFormat dd = new SimpleDateFormat("dd");
	public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
	public static final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss");
	public static final SimpleDateFormat FMT_FN = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static void main(String[] args) {
		//创建时间
		long time =  Long.valueOf("1562415587000");

		long time1 =  Long.valueOf("1562415588000");
		String createTime = FMT_FN.format(new Date(time));
		String createTime1 = FMT_FN.format(new Date(time1));
		System.out.println(createTime);
		System.out.println(createTime1);
	}
	/**
	 * 格式化日期
	 * 
	 * @param pattern
	 * @param date
	 * @return
	 */
	public static String formatDate(String pattern, Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	/**
	 * 字符串转化日期
	 * 
	 * @param pattern
	 * @param date
	 * @return
	 */
	public static Date parseDate(String pattern, String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			return sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加或减少天数
	 * 
	 * @param dayNum
	 * @param date
	 * @return
	 */
	public static Date addDay(int dayNum, Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, dayNum);
		return calendar.getTime();
	}

	/**
	 * 获取两个日期相差的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int differentDays(Date date1, Date date2) {
		try{
			String yyyyMMdd1 = yyyyMMdd.format(date1);
			String yyyyMMdd2 = yyyyMMdd.format(date2);

			long days = (yyyyMMdd.parse(yyyyMMdd1).getTime() - yyyyMMdd.parse(yyyyMMdd2).getTime()) / 1000 / 60 / 60 / 24;

			return (int) days;
		}catch(Exception e){
			log.error("获取两个日期相差的天数", e);
		}
		return -1;
	}

	/**
	 * 获取当前时间当月的最大天数
	 * 
	 * @param date
	 * @return
	 */
	public static int getMaxDays(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}
}